﻿using System;
using System.Windows;
using System.Windows.Controls;

namespace EnsureWeb.Share
{
    public class UIValidation
    {
        public static bool HasError(FrameworkElement e)
        {
            if (e is TextBox)
            {
                var tb = e as TextBox;
                if (tb.Text.IsEmpty())
                {
                    tb.Text = " ";
                    tb.Text = string.Empty;
                }
            }

            if (e is PasswordBox)
            {
                var pb = e as PasswordBox;
                if (pb.Password.IsEmpty())
                {
                    pb.Password = " ";
                    pb.Password = string.Empty;
                }
            }
            
            foreach (ValidationError error in Validation.GetErrors(e))
            {
                if (e is Control)
                    (e as Control).Focus();

                return true;
            }

            return false;
        }

        public static bool HasError(Panel p)
        {
            foreach (var child in p.Children)
            {
                if (child is Panel)
                {
                    if(HasError((Panel)child))
                        return true;
                }
                else if (child is ContentControl)
                {
                    var content = (child as ContentControl).Content;
                    if (content is Panel)
                    {
                        if (HasError((Panel)content))
                            return true;
                    }
                    else if (content is FrameworkElement)
                    {
                        if (HasError((FrameworkElement)content))
                            return true;
                    }
                }
                else if (child is FrameworkElement)
                {
                    if( HasError((FrameworkElement)child))
                       return true;
                }
            }

            return false;
        }
    }
}
